package com.pompinator;
import gummy.database.access.ConnectionSettingsPool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import nl.ansuz.android.steam.dota.response.match.GetMatchDetailsResponse;
import nl.ansuz.android.steam.util.GsonUtil;

import com.google.gson.Gson;
import com.pompom.matchcrawler.MatchPersistor;
import com.pompom.matchcrawler.SkillMapBuilder;


public class DataPumper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MatchPersistor mp = new MatchPersistor() ;
		mp.setBufferSize(300);
		int lineNumber=0;
		long matchid = 0;
		try {
		InputStream    fis;
		BufferedReader br;
		String         line;

		ConnectionSettingsPool.getInstance().loadConnections(MatchPersistor.class.getResourceAsStream("/database.xml"));
		SkillMapBuilder.build(new File("skillmap.map"));
		fis = new FileInputStream(args[0]);
		br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
	
		GsonUtil gsonUtil = new GsonUtil();
		Gson gson = new Gson();
		
		while ((line = br.readLine()) != null) {
		   lineNumber++;
		   String s = treatString(line) ;

			
			GetMatchDetailsResponse getMatchDetailsResponse = gson.fromJson(gsonUtil.getStrippedDotaResult(s), GetMatchDetailsResponse.class);
			long antes = System.currentTimeMillis();
			mp.persist(getMatchDetailsResponse);
			 antes = System.currentTimeMillis() - antes;
			matchid = getMatchDetailsResponse.matchId;
			System.out.println("persisted "+getMatchDetailsResponse.matchId+ "   ln "+lineNumber+" in "+antes);
			
		  
		}

		// Done with the file
		br.close();
		br = null;
		fis = null;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.out.println(" last line "+lineNumber+"  match "+matchid);
		}


	}
	
	private static String treatString(String s)
	{
		int a = s.indexOf("},");
		String b = "{ \"result\": { "+s.substring(a+2);
		int c = b.indexOf("start_time\" : { \"$date\" :");
		 
		String temp1 = b.substring(c+26, c+36);
		
		String almost = b.substring(0, c+13) + temp1 +  b.substring(c+41)+" }";
		
		
		//troca radiant_team de boolean pra int
		if (almost.contains("radiant_team_complete"))
		{
			almost = almost.replace("\"radiant_team_complete\" : true", "\"radiant_team_complete\" : 1");
			almost = almost.replace("\"radiant_team_complete\" : false", "\"radiant_team_complete\" : 0");
			almost = almost.replace("\"dire_team_complete\" : true", "\"dire_team_complete\" : 1");
			almost = almost.replace("\"dire_team_complete\" : false", "\"dire_team_complete\" : 0");	
			
			
		}
		
		//System.out.println(almost); 
		return almost;
	}

}
